package com.chinackts.auth.repository.redis;

import com.alibaba.fastjson.JSON;
import com.chinackts.auth.model.HeaderStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author Lianhong
 * @since 2021/10/27
 */
@Repository
public class HeaderStoreRepository {

    @Resource
    private StringRedisTemplate redisTemplate1;

    private static final String KEY = "%s:header";

    @Value("${e-port.redis.timeout}")
    private long timeout;

    /**
     * 获取header
     *
     * @param id 用户标识
     */
    public List<HeaderStore> getHeaders(String id) {
        HashOperations<String, String, String> ops = this.redisTemplate1.opsForHash();
        List<String> headers = ops.values(String.format(KEY, id));
        return CollectionUtils.isEmpty(headers) ? new ArrayList<>() : JSON.parseArray(headers.toString(), HeaderStore.class);
    }

    /**
     * 存储header
     *
     * @param id 用户标识
     */
    public void setHeader(String id, HeaderStore header) {
        HashOperations<String, String, String> ops = this.redisTemplate1.opsForHash();
        ops.put(String.format(KEY, id), header.getName(), JSON.toJSONString(header));
        Long expire = redisTemplate1.getExpire(String.format(KEY, id));
        if (expire == null || expire < 0L) this.expire(id);
    }

    /**
     * 存储header
     *
     * @param id 用户标识
     */
    public void setHeaders(String id, List<HeaderStore> headers) {
        HashOperations<String, String, String> ops = this.redisTemplate1.opsForHash();
        Map<String, String> headerMap = new HashMap<>();
        for (HeaderStore s : headers) {
            headerMap.put(s.getName(), JSON.toJSONString(s));
        }
        ops.putAll(String.format(KEY, id), headerMap);
        Long expire = redisTemplate1.getExpire(String.format(KEY, id));
        if (expire == null || expire < 0L) this.expire(id);
    }

    /**
     * 删除headers
     *
     * @param id 用户标识
     */
    public void deleteHeaders(String id, Object... keys) {
        HashOperations<String, String, String> ops = this.redisTemplate1.opsForHash();
        ops.delete(String.format(KEY, id), keys);
    }

    /**
     * 设置header到期时间
     *
     * @param id 用户标识
     */
    public void expire(String id) {
        this.redisTemplate1.expire(String.format(KEY, id), timeout, TimeUnit.HOURS);
    }

}
